/**
 * 统一请求后台方法
 * @param url
 * @param data
 * @param callback 回调
 * @param setting ajax参数
 */
function request(url, data, callback, setting) {
    var nonce = uuid(32,16);
    var temp = {
        "nonce": nonce,
        "version": "1.0",
        // "timestamp": "20181221101453261",
        "timestamp": new Date().format('yyyyMMddhhmmss'),
        "body": {},
        "signature": md5Key(nonce),
        "token": null
    };
    console.log('temp',temp);

    var s = {
        data: data,
        dataType:'json',//服务器返回json格式数据
        type:'post',//HTTP请求类型
        timeout:10000,//超时时间设置为10秒；
        headers:{'Content-Type':'application/json'},
        success:function(data){
            //服务器返回响应，根据响应结果，分析是否登录成功；
            if(data.code == 'S0000'){
                callback(data);
            }else{
                //异常处理；
                console.error(data);
            }
        },
        error:function(xhr,type,errorThrown){
            //异常处理；
            console.log(type);
        }
    };
    if (setting) {
        for (var key in setting) {
            s[key]= setting[key];
        }
    }

    mui.ajax(url,s);
}

//获取Url参数
function getpara(){
    var obj = {};
    var url=document.URL;
    var para="";
    if(url.lastIndexOf("?")>0){
        para=url.substring(url.lastIndexOf("?")+1,url.length);
        var arr=para.split("&");
        para="";
        for(var i=0;i<arr.length;i++){
            var key = arr[i].split("=")[0];
            var name = arr[i].split("=")[1];
            obj[key] = name;
        }
    }
    return obj;
}

/**
 * 生成底部导航栏
 */
function createNav(flag,activeIndex) {
    var table = document.body;
    var li = document.createElement('nav');
    var path = flag ? '' : '../../';

    li.className = 'mui-bar mui-bar-tab';
    li.innerHTML = '<a class="mui-tab-item" href="'+path+'index.html">' +
        '        <span class="fa fa-bank fa-fw"></span>' +
        '        <span class="mui-tab-label">首页</span>' +
        '    </a>' +
        '    <a class="mui-tab-item" href="'+path+'pages/performance/performance.html">' +
        '        <span class="fa fa-bar-chart fa-fw"></span>' +
        '        <span class="mui-tab-label">业绩</span>' +
        '    </a>' +
        '    <a class="mui-tab-item" href="'+path+'pages/contacts/contacts.html">' +
        '        <span class="fa fa-address-book-o fa-fw">' +
        '        </span>' +
        '        <span class="mui-tab-label">通讯录</span>' +
        '    </a>' +
        '    <a class="mui-tab-item" href="'+path+'pages/admin/my.html">' +
        '        <span class="fa fa-user-md fa-fw"></span>' +
        '        <span class="mui-tab-label">我</span>' +
        '    </a>';
    table.appendChild(li);
    // 事件绑定
    mui('nav .mui-tab-item').each(function (index,item) {
        mui(item)[0].className = 'mui-tab-item';
        if(index == activeIndex){
            mui(item)[0].className = 'mui-tab-item mui-active';
        }
        mui(this)[0].addEventListener('tap',function () {
           // console.log('sdfff--'+this.getAttribute('href'));
           location.href = this.getAttribute('href');
       })
    });

}

/**
 * 报文随机串
 * @param len 指定长度和基数
 * @param radix
 * @returns {string}
 */

function uuid(len, radix) {

    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

    var uuid = [], i;

    radix = radix || chars.length;


    if (len) {

        // Compact form

        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];

    } else {

        // rfc4122, version 4 form

        var r;


        // rfc4122 requires these characters

        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';

        uuid[14] = '4';


        // Fill in random data.  At i==19 set the high bits of clock sequence as

        // per rfc4122, sec. 4.1.5

        for (i = 0; i < 36; i++) {

            if (!uuid[i]) {

                r = 0 | Math.random() * 16;

                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];

            }

        }

    }


    return uuid.join('');

}


/**
 * 得到 MD5签名key
 * @param arrs
 * @returns {Array}
 */
function md5Key(str) {
    var arr = [];
    var arrs = str.split('');
    arrs.forEach(function (item, index) {
        // console.log('index % 2',index % 2)
        if (index % 2 != 0) {
            arr.push(item);
        }
    })
    // return arr;
    // return arr.reverse().join('');
    return CryptoJS.MD5(arr.reverse().join('')).toString();
}

/**
 * 3des加密
 * @param str
 * @param key
 * @param iv
 * @returns {string}
 */
function des_encrypt(str, key, iv) {
    var key = CryptoJS.MD5(key).toString();
    var iv = CryptoJS.MD5(iv).toString();
    var crypto_key = CryptoJS.enc.Utf8.parse(key);
    var crypto_iv = CryptoJS.enc.Utf8.parse(iv.substr(0, 8));

    //console.log(crypto_key.toString(CryptoJS.enc.Utf8));
    //console.log(crypto_iv.toString(CryptoJS.enc.Utf8));
    var encode_str = CryptoJS.TripleDES.encrypt(str, crypto_key, {
        iv: crypto_iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encode_str.toString();
}

/**
 * 3des解密
 * @param str
 * @param key
 * @param iv
 * @returns {string}
 */
function des_decrypt(str, key, iv) {
    var key = CryptoJS.MD5(key).toString();
    var iv = CryptoJS.MD5(iv).toString();
    var crypto_key = CryptoJS.enc.Utf8.parse(key);
    var crypto_iv = CryptoJS.enc.Utf8.parse(iv.substr(0, 8));
    var decrypt_str = CryptoJS.TripleDES.decrypt(str, crypto_key, {
        iv: crypto_iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypt_str.toString(CryptoJS.enc.Utf8);
}

//日期格式化
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
        // millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
